package com.mingqijia.gassafety.webserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.DictionaryMapper;
import com.mingqijia.gassafety.db.mapper.auth.CompanyMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.webserver.response.CompanyResponse;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织架构 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-04-28
 */
@Service
@Slf4j
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyEntry> implements CompanyService {
    @Autowired
    DictionaryMapper dictionaryMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    /**
     * 数据来源，0-系统生成,1-vcc
     */
    private static final Integer source = 1;

    @Override
    public String getOrgCode(String spId,String subsCode) {
        log.info("getOrgCode-consumer:{},{}", spId,subsCode);
        if (!StringUtils.isEmpty(subsCode)){
            Consumer consumer=consumerMapper.selectByOrgCode(subsCode,spId);
            log.info("getOrgCode-consumer:{}", JSONObject.toJSON(consumer));
            if (consumer!=null&&!StringUtils.isEmpty(consumer.getOrgCode()))
                return consumer.getOrgCode();
        }

        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getId,spId).eq(CompanyEntry::getIsDeleted,0)
                    .eq(CompanyEntry::getSource,source);
        List<CompanyEntry> list = this.list(queryWrapper);
        String orgCode = "";
        if (list.isEmpty()) {
            return "";
        } else {
            orgCode = list.get(0).getCode();
        }
        LambdaQueryWrapper<Dictionary> dictQueryWrapper = new LambdaQueryWrapper<>();
        dictQueryWrapper.eq(Dictionary::getDictCode,"org_map").eq(Dictionary::getIsDeleted,0)
                .eq(Dictionary::getValue,orgCode);
        List<Dictionary> dictList = dictionaryMapper.selectList(dictQueryWrapper);
        if (dictList.isEmpty()) return orgCode;
        if (StringUtils.isEmpty(dictList.get(0).getDescription())) {
            return orgCode;
        } else {
            return dictList.get(0).getDescription();
        }
    }

    @Override
    public List<String> getOrgCodeBySubsCode(String spId) {
        log.info("getOrgCodeBySubsCode-param:{}",spId);
        List<String> orgCodes = new ArrayList<>();
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getId,spId).eq(CompanyEntry::getIsDeleted,0)
                .eq(CompanyEntry::getSource,source);
        List<CompanyEntry> list = this.list(queryWrapper);
        String orgCode = "";
        if (list.isEmpty()) {
            return orgCodes;
        } else {
            orgCode = list.get(0).getCode();
            orgCodes.add(orgCode);
        }
        LambdaQueryWrapper<Dictionary> dictQueryWrapper = new LambdaQueryWrapper<>();
        dictQueryWrapper.eq(Dictionary::getDictCode,"org_map_subsCode").eq(Dictionary::getIsDeleted,0)
                .eq(Dictionary::getValue,orgCode);
        List<Dictionary> dictList = dictionaryMapper.selectList(dictQueryWrapper);
        if (dictList.isEmpty()) return orgCodes;
        if (StringUtils.isEmpty(dictList.get(0).getDescription())) {
            return orgCodes;
        } else {
            dictList.forEach(dictionary -> {
                orgCodes.add(dictionary.getDescription());
            });

            return orgCodes;
        }
    }

    /**
     * 反向查询orgCode映射的从orgCode，根据从orgCode查询spId
     * @Description Dictionary表org_map中，value是新建的企业（在TC无对应orgcode），description是正常的企业（在TC有对应orgcode）
     * @param subOrgCode
     * @return
     */
    @Override
    public String getSpId(String subOrgCode) {
        log.info("subOrgCode:" + subOrgCode);
        LambdaQueryWrapper<Dictionary> dictQueryWrapper = new LambdaQueryWrapper<>();
        dictQueryWrapper.eq(Dictionary::getDictCode,"org_map").eq(Dictionary::getIsDeleted,0)
                .eq(Dictionary::getDescription,subOrgCode);
        List<Dictionary> dictList = dictionaryMapper.selectList(dictQueryWrapper);
        String orgCode = "";
        if (dictList.isEmpty() || StringUtils.isEmpty(dictList.get(0).getValue())) {
            orgCode = subOrgCode;
        } else {
            orgCode = dictList.get(0).getValue();
        }

        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getCode,orgCode).eq(CompanyEntry::getIsDeleted,0)
                .eq(CompanyEntry::getSource,source);
        List<CompanyEntry> list = this.list(queryWrapper);
        log.info( "orgCode :"+orgCode );
        String spId = "";
        if (list.isEmpty()) {
            throw new BizException( orgCode+"未查询到对应公司spId" );
        } else {
            spId = list.get(0).getId();
        }
        return spId;
    }

    @Override
    public List<String> findSpIdWithNoDict() {
        log.info("开始执行企业字典生成逻辑。。");

        QueryWrapper<CompanyEntry> queryClause = new QueryWrapper<>();
        queryClause.lambda().eq(CompanyEntry::getIsDeleted, YesNoEnum.N.getCode())
                .notExists("select 1 from t_gss_configure where is_deleted=0 and sp_id=t_gss_company.id");

        List<CompanyEntry> entries = this.list(queryClause);
        if (CollectionUtils.isEmpty(entries)) {
            return Collections.emptyList();
        }
        return entries.stream().map(CompanyEntry::getId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<CompanyResponse> getCompanyList() {
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getIsDeleted, Constants.IS_DELETED_FALSE)
                .orderByDesc(CompanyEntry::getCreatedAt);
        List<CompanyEntry> list = this.list(queryWrapper);
        List<CompanyResponse> resultList = list.stream().map(item -> {
            CompanyResponse companyResponse = new CompanyResponse();
            companyResponse.setSpId(item.getId());
            companyResponse.setName(item.getName());
            return companyResponse;
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public String getCompanyName(String spId) {
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(CompanyEntry::getId, spId);
        CompanyEntry companyEntry = this.getOne(queryWrapper);
        if (companyEntry != null){
            return companyEntry.getName();
        }
        return null;
    }

    @Override
    public String getCompanyNameByOrgCode(String jvOrgCode) {
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(CompanyEntry::getId, jvOrgCode);
        CompanyEntry companyEntry = this.getOne(queryWrapper);
        if (companyEntry != null){
            return companyEntry.getName();
        }
        return null;

    }


    @Override
    public String getOrgCodeBySpId(String orgCode) {
        LambdaQueryWrapper<Dictionary> dictQueryWrapper = new LambdaQueryWrapper<>();
        dictQueryWrapper.eq(Dictionary::getDictCode,"org_map_subsCode").eq(Dictionary::getIsDeleted,0)
                .eq(Dictionary::getDescription,orgCode);
        List<Dictionary> dictList = dictionaryMapper.selectList(dictQueryWrapper);
        if (dictList.isEmpty()) return orgCode;
        if (StringUtils.isEmpty(dictList.get(0).getValue())) {
            return orgCode;
        } else {
            return dictList.get(0).getValue();
        }
    }

    @Override
    public List<CompanyResponse> queryCompanyNameList(List<String> spIds) {
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(CompanyEntry::getId, spIds)
                .orderByDesc(CompanyEntry::getCreatedAt);
        List<CompanyEntry> list = this.list(queryWrapper);
        List<CompanyResponse> resultList = list.stream().map(item -> {
            CompanyResponse companyResponse = new CompanyResponse();
            companyResponse.setSpId(item.getId());
            companyResponse.setName(item.getName());
            return companyResponse;
        }).collect(Collectors.toList());
        return resultList;
    }

}
